package com.test.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.test.pay.alipay.AlipayConfig;
import com.test.pay.pojo.Order;
import com.test.pay.service.OrderService;
import com.test.pay.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class AlipayController {
    @Autowired
    private OrderService orderService;

    @RequestMapping("pay.html")
    public void order(HttpServletRequest request, HttpServletResponse response, String orderNum) throws Exception {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        if (orderNum != null) {
            Order order = orderService.getOrderByOrderNum(orderNum);
            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = orderNum;
            // 订单名称，必填
            String subject ="测试订单";
            // 付款金额，必填
            Float amount = order.getAmount() / 100F;//从分变成元
            String total_amount = amount.toString();
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            String body = "";

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(result);
            //输出
            //out.println(result);
            response.setContentType("text/html;charset=" + AlipayConfig.charset);
            out.println(result);//直接将完整的表单html输出到页面
            out.flush();
            out.close();
        }
    }

    @RequestMapping("return.html")
    public String returnPage(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            //该页面可做页面美工编辑
            //Order order = orderService.getOrderByOrderNum(orderNum);
            //判断交易状态，判断支付金额
            System.out.println("交易状态：" + params.get("trade_status"));
            System.out.println("支付金额：" + params.get("total_amount"));
            return "success.jsp";
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
        } else {
            //该页面可做页面美工编辑
            return "fail.jsp";
        }

    }

    @RequestMapping("callback.html")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("===============================");
        System.out.println("支付回调");
        PrintWriter out = response.getWriter();
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        for (String s : params.keySet()) {
            System.out.println(s+"="+params.get(s));
        }
        System.out.println("=======================");
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
    1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");


            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            Order order = orderService.getOrderByOrderNum(out_trade_no);
            if (order == null) {
                out.println("fail");
                return;
            }
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                String sellerId = params.get("seller_id");
                if (!sellerId.equals("2088102170174522")) {//如果商户号一致，代表是我收的钱
                    out.println("fail");
                    return;
                }
                Float totalFee = Float.valueOf(params.get("total_amount")) * 100;//交易金额，单位是元,需要转化成分
                int amount = totalFee.intValue();


                if (order.getStatus() == Constants.ORDER_STATUS_SUCCESS) {//如果是已经处理过的订单,则不处理
                    out.println("success");
                    return;
                }
                if (order.getAmount().equals(amount)) {//金额一致
                    order.setStatus(Constants.ORDER_STATUS_SUCCESS);
                    order.setResultDate(new Date());
                    order.setTradeNum(trade_no);
                    order.setResult(trade_status);
                    orderService.updateOrder(order);
                    //加话费、发游戏道具。。。。通知卖家。。。。
                }
                //注意：
                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            } else {
                order.setStatus(Constants.ORDER_STATUS_FAIL);
                order.setResultDate(new Date());
                order.setTradeNum(trade_no);
                order.setResult(trade_status);
                orderService.updateOrder(order);
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            out.flush();
            out.println("success");    //请不要修改或删除
            //////////////////////////////////////////////////////////////////////////////////////////
        } else {//验证失败
            System.out.println("签名失败");
            out.println("fail");
        }
    }

    public static void main(String[] args) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, "RSA2");
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("我是测试数据");
        model.setSubject("App支付测试Java");
        model.setOutTradeNo(System.currentTimeMillis()+"");
        model.setTimeoutExpress("30m");
        model.setTotalAmount("0.01");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl("商户外网可以访问的异步地址");
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }
}
